/*
 * Copyright (c) 2010-2011 Josef Hardi <josef.hardi@gmail.com>
 * Copyright (c) 2010 Piotr Zagawa <piotr.zagawa@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package id.duapuluhdua.dakidaki;

import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

import id.duapuluhdua.dakidaki.activities.ActivityMain;
import id.duapuluhdua.dakidaki.common.CommonActivity;
import id.duapuluhdua.dakidaki.common.CommonThread;

/**
 *
 */
public class MainThread extends CommonThread
{
  /** Constants */
  private static final String TAG = "MainThread";
  private static final int TIME_GAP = 100; // miliseconds.

  /** Fields */
  private SurfaceHolder mSurfaceHolder;
  private MainDraw mDraw;

  // Time elapsed between frames
  private long mLastFrameTime;

  /**
   * The default constructor.
   *
   * @param holder
   * @param parent
   * @param handler
   */
  public MainThread(SurfaceHolder holder, CommonActivity parent, Handler handler)
  {
    super(parent, handler);

    mSurfaceHolder = holder;
    mDraw = new MainDraw(parent);

    mLastFrameTime = 0;
  }

  public void setSurfaceSize(int width, int height)
  {
    mDraw.surfaceSizeChanged(width, height, this.getScreenOrientation());
  }

  /**
   * Initializes the layers.
   */
  @Override
  public void onInitializeData()
  {
    mDraw.initData();
  }

  /**
   * Run the thread.
   */
  @Override
  public void run()
  {
    super.run();

    // Run the animation loop
    while (this.isActive()) {
      if (this.isRunning())
      {
        Canvas canvas = null;
        try {
          canvas = mSurfaceHolder.lockCanvas();
          if (isEnabled()) {
            updateLoop();
            if (canvas != null) {
              mDraw.doDraw(canvas);
            }
          }
        }
        finally {
          if (canvas != null)
            mSurfaceHolder.unlockCanvasAndPost(canvas);
        }
      }
      else {  // put sleep the thread if it is not running.
        try {
          Thread.sleep(50);
        }
        catch (InterruptedException e) {
          // Do nothing.
        }
      }
    }
  }

  private void updateLoop()
  {
    // Get the current time.
    final long timeNow = System.currentTimeMillis();

    // Start delay by 100ms
    if (mLastFrameTime > timeNow)
      return;

    // Update objects here
    mDraw.updateObjectsState();

    // Update tracks
    ActivityMain.loader.updateObjectsState();

    // Update last frame time
    mLastFrameTime = timeNow;
  }

//  protected boolean onTouchEvent(View view, MotionEvent event)
//  {
//     return mDraw.onTouchEvent(view, event);
//  }

  protected boolean onDownEvent(MotionEvent e)
  {
    return mDraw.onDownEvent(e);
  }

  protected boolean onActionUpEvent(MotionEvent e)
  {
    return mDraw.onActionUpEvent(e);
  }

  protected boolean onScrollEvent(float dx, float dy)
  {
    return mDraw.onScrollEvent(dx, dy);
  }

  /**
   * Records the running frame time.
   */
  @Override
  public void onStateChanged()
  {
    if (isRunning())
      mLastFrameTime = System.currentTimeMillis() + TIME_GAP;
  }

  public Bundle saveState(Bundle map)
  {
    if (map != null) {
      // map.put...
    }
    return map;
  }

  public void restoreState(Bundle savedInstanceState)
  {
    if (savedInstanceState != null) {
      Log.i(TAG, "Restore state from the Bundle.");
    }
  }
}
